#include "groupmodel.h"

#include "groupmodel.h"
#include <QDebug>
#include "groupitem.h"
#include "baza/grupa.h"

GroupModel::GroupModel(QObject *parent)
    : QAbstractListModel(parent)
{
    QHash<int, QByteArray> roles;

    roles[RoleGroupName]="name";
    roles[RoleId]="id";
    roles[RoleIndex] = "index";
    roles[RolePriority] = "priority";

    setRoleNames(roles);
}

void GroupModel::addGroup(const Grupa &grupa, int index){
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_groupItems << new GroupItem(grupa.dajId(), grupa.dajImeGrupe(), index, grupa.dajPrioritetGrupe());

    connect(m_groupItems.last(), SIGNAL(dataChanged()), SLOT(handleItemChange()));

    qDebug()<<"dodajem grupu"<<grupa.dajImeGrupe();
    endInsertRows();
    emit countChanged(m_groupItems.count());
}

int GroupModel::rowCount(const QModelIndex & parent) const  {
    return m_groupItems.count();
}

int GroupModel::count(){
    return m_groupItems.count();
}

void GroupModel::clear(){
    int currentCount=m_groupItems.count();
    for (int i=0; i<currentCount; i++)
    {
        beginRemoveRows(QModelIndex(), 0, 0);

        GroupItem* item=m_groupItems.takeFirst();
        delete item;

        emit countChanged(m_groupItems.count());

        endRemoveRows();
    }
}

GroupItem* GroupModel::get(int index){
    return m_groupItems[index];
}

QVariant GroupModel::data(const QModelIndex & index, int role) const  {
    if (index.row() < 0 || index.row() > m_groupItems.count())
        return QVariant();

    GroupItem* group=m_groupItems[index.row()];

    if (role == RoleGroupName)
        return group->name();
    else if (role == RoleId)
        return group->groupId();
    else if (role == RoleIndex)
        return group->groupIndex();
    else if (role == RolePriority)
        return group->groupPriority();

    return QVariant();
}

QModelIndex GroupModel::indexFromItem(const GroupItem *item) const
{
    Q_ASSERT(item);
    for(int row=0; row<m_groupItems.size(); ++row) {
        if(m_groupItems.at(row) == item) return index(row);
    }
    return QModelIndex();
}

void GroupModel::handleItemChange()
{
    GroupItem* item = static_cast<GroupItem*>(sender());
    QModelIndex index = indexFromItem(item);
    if(index.isValid())
        emit dataChanged(index, index);
}
